package onlinebanking.server.modules;

import onlinebanking.constants.MSG;
import onlinebanking.exceptions.UserNotLoggedInException;
import onlinebanking.network.Message;
import onlinebanking.server.ServerEngine;
import onlinebanking.server.objects.BankAccount;
import onlinebanking.server.objects.Session;

public class AccountBalanceModule extends Module {

	public AccountBalanceModule(ServerEngine se, Message message) {
		this.serverengine = se;
		this.message = message;
	}

	public Message handleRequest() {
		Message response;
		try {
			if (serverengine.isLoggedIn()) {

				response = new Message();
				response.setMsgType(MSG.BALANCE_RESPONSE);

				Session session = serverengine.getSession();

				BankAccount activeBA = session.getActiveBankAccount();

				if (activeBA == null) {

					response.setSuccess(false);
					response.addAttribute("reason", "No bank accounts");
				} else {

					double balance = activeBA.getBalance();
					response.setSuccess(true);
					response.addAttribute("balance", balance);
					response.addAttribute("accountno", activeBA.getAccountno());
				}

			} else {
				response = new Message();
				response.setAsUserNotLoggedIn();
			}
		} catch (UserNotLoggedInException e) {
			response = new Message();
			response.setAsUserNotLoggedIn();
		}
		return response;
	}
}
